package com.syl.generator.common.util;

import org.yaml.snakeyaml.Yaml;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * @author syl
 * @create 2018-03-23 14:28
 **/
public class ConfigReadUtil {
    private static Yaml yaml = new Yaml();
    private static URL url = Thread.currentThread().getContextClassLoader().getResource("config.properties");
    private static URL urlYML = Thread.currentThread().getContextClassLoader().getResource("config.yml");

    public static Integer getYmlInteger(String path){
        return Integer.valueOf(getYmlString(path));
    }

    public static boolean getYmlBoolean(String path){
        return Boolean.valueOf(getYmlString(path,false));
    }

    public static boolean getYmlBoolean(String path,boolean defaultValue){
        return Boolean.valueOf(getYmlString(path,defaultValue));
    }

    public static String getYmlString(String path){
        return getYmlObject(path,"").toString();
    }

    public static String getYmlString(String path,Object defaultValue){
        return getYmlObject(path,defaultValue).toString();
    }

    public static List<String> getYmlStringList(String path){
        List<String> list = (List<String>) getYmlObject(path,null);
        return list;
    }

    public static Object getYmlObject(String path,Object defaultValue){
        String[] split = path.split("\\.");
        try {
            Map map  =(Map)yaml.load(new FileInputStream(urlYML.getFile()));
            for (int i=0;i<split.length;i++){
                String str = split[i];
                if(i < split.length-1)
                    map = (Map) map.get(str);
                else {
                    Object o = map.get(str);
                    return o == null ? defaultValue : o;
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return defaultValue;
    }

    public static String getValue(String key){
        return getValue(key,url.getPath());
    }

    public static String getValueDefault(String key,String defaultStr){
        String value = getValue(key, url.getPath());
        return StringUtils.isEmpty(value) ? defaultStr : value;
    }

    public static Integer getValueInteger(String key){
        String value = getValue(key);
        return Integer.valueOf(value);
    }

    public static String getValue(String key,String filePath){
        Properties prop = new Properties();
        try {
            prop.load(new FileInputStream(new File(filePath)));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return prop.getProperty(key);
    }

}
